package com.cnh.o2o.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cnh.o2o.dao.ProductCategoryDao;
import com.cnh.o2o.dao.ProductDao;
import com.cnh.o2o.dto.ProductCategoryExecution;
import com.cnh.o2o.entity.ProductCategory;
import com.cnh.o2o.enums.ProductCategoryStateEnum;
import com.cnh.o2o.exceptions.PrductCategoryOperationException;
import com.cnh.o2o.exceptions.ProductOperationException;
import com.cnh.o2o.service.ProductCategoryService;

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {

	@Autowired
	private ProductCategoryDao productCategoryDao;
	
	@Autowired
	private ProductDao productDao;
	
	@Override
	public List<ProductCategory> getProductCategoryList(long shopId) {
		
		return productCategoryDao.queryProductCategoryList(shopId);
	}
	@Override
	@Transactional
	public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList)
			throws PrductCategoryOperationException {
		if(productCategoryList != null && productCategoryList.size() > 0){
			try {
				int effectedNum = productCategoryDao.batchInsertProductCategory(productCategoryList);
				if(effectedNum <= 0){
					throw new PrductCategoryOperationException("店铺类别创建失败");
				} else {
					return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
				}
			} catch (Exception e) {
				throw new PrductCategoryOperationException("batchAddProductCategory error : " + e.getMessage());
			}
		} else {
			return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);
		}
	}
	@Override
	@Transactional
	public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId)
			throws PrductCategoryOperationException {
		//解除该productCategoryId与tb_product中商品的关联
		try{
			int effectedNum = productDao.updateProductCategoryToNull(productCategoryId);
			if(effectedNum < 0){
				throw new ProductOperationException("商品类别更新失败");
			}
		}catch (Exception e) {
			throw new PrductCategoryOperationException("deleteProductCategory error : " + e.toString());
		}
		
		//删除该productCategory
		try {
			int effectedNum = productCategoryDao.deleteProductCategroy(productCategoryId, shopId);
			if(effectedNum <= 0){
				throw new PrductCategoryOperationException("商品类别删除失败");
			} else {
				return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new PrductCategoryOperationException("deleteProductCategory error : " + e.getMessage());
		
		}
	}
	

}
